import {
  findProjectInfo,
  getCompanys,
  findUserInfo,
  getProjProgress,
  getProjandModelNum,
  getProjectProgressStat,
} from '@/services/kanbanServices';
// todo展示数据
import {
  getBuildingStatus,
  getProduceValueAndCalculate,
  listAllSafetyIndex,
} from '@/services/bimServices';

import { jsapi, viewUtils } from '@/utils/arcgis';
// import { statusArr, sizeArr } from '@/constants/projDoc';
import moment from 'moment';
import { initEchartsLayer } from '@/components/content/mainPage/chartLayer/init.js';

let highlightSelect = [];
// window.highlightSelect = [];
let _projectListLayer = null;
let queryStations = null;

const buildingStatusList = [
  {
    title: '未开始',
    color: [255, 255, 255, 0.05], // 隐藏
    // color: [254, 177, 81, 0.6],
  },
  {
    title: '未开始（延期）',
    color: [254, 103, 81, 1],
  },
  {
    title: '执行中',
    color: [61, 251, 255, 1],
  },
  {
    title: '执行中（延期）',
    color: [61, 152, 255, 1],
  },
  {
    title: '已完成',
    color: [61, 255, 159, 1],
  },
  {
    title: '已完成（提前）',
    color: [158, 255, 61, 1],
  },
  {
    title: '已完成（延期）',
    color: [232, 61, 255, 1],
  },
];

const buildingStatusTable = buildingStatusList.reduce(
  (r, e) => {
    r[e.title] = e.color;
    return r;
  },
  { default: buildingStatusList[0].color },
);

var iconRenderer2 = {
  // type: 'simple',
  type: 'unique-value',
  field: 'projectId',
  defaultSymbol: {
    type: 'point-3d',
    symbolLayers: [
      {
        type: 'icon',
        resource: {
          href: './images/mark.svg',
        },
        size: 190,
        outline: {
          color: 'white',
          size: 2,
        },
        anchor: 'relative',
        anchorPosition: {
          x: 0,
          y: 0.5,
        },
      },
    ],
  },
  uniqueValueInfos: [
    {
      // All features with value of "North" will be blue
      value: '1308246635895685122',
      symbol: {
        type: 'point-3d',
        symbolLayers: [
          {
            type: 'icon',
            resource: {
              // href: './images/base_map.png',
              href: './images/mark_red.svg',
            },
            size: 190,
            outline: {
              color: 'white',
              size: 2,
            },
            anchor: 'relative',
            anchorPosition: {
              x: 0,
              y: 0.5,
            },
          },
        ],
      },
    },
    {
      // 最滞后
      value: '1307552536842551297',
      symbol: {
        type: 'point-3d',
        symbolLayers: [
          {
            type: 'icon',
            resource: {
              href: './images/mark_yellow.svg',
            },
            size: 190,
            outline: {
              color: 'white',
              size: 2,
            },
            anchor: 'relative',
            anchorPosition: {
              x: 0,
              y: 0.5,
            },
          },
        ],
      },
    },
  ],
  __projectIdToIndex: {},
};

// 浏览器端自定义一个featurelayer图层
async function createProjectListLayer(graphics) {
  const [FeatureLayer, PopupTemplate] = await jsapi.load([
    'esri/layers/FeatureLayer',
    'esri/PopupTemplate',
  ]);

  const renderPoiPopup = attributes => {
    const {
      areaCode = '--',
      OBJECTID,
      name,
      prjStatus,
      company,
      invest,
      buildArea,
      startDate,
      completeDate,
      safeCivilizationIndex,
      category,
      totalWorkTime,
      projectName,
      produceValue,
      lat,
      lng,
      workPeriodString,
      workPeriodPercent,
      safeNum,
    } = attributes;
    let _progressValue = 0;
    try {
      // _progressValue = Math.round((produceValue * 100) / invest);
    } catch (error) {}
    // _progressValue = _progressValue > 100 ? 100 : _progressValue;
    return ` <div class="c-popup">
        <div class="c-popup-status">${prjStatus}</div>
        <div class="c-popup-chart">
          ${workPeriodPercent}
        </div>
        <p class="c-popup-p">
        建设单位 <span>${company}</span>
        </p>
        <p class="c-popup-p">
          工期 <span>${`${workPeriodString}`}</span>
        </p>

        <p class="c-popup-p">
          项目类型 <span>${category} </span>
        </p>
        <p class="c-popup-p">
          项目投资 <span>${invest} 万元</span>
        </p>
        <p class="c-popup-p">
          安全生产指数 <span>${safeNum} </span>
        </p>
        <div class="c-popup-footer">
          <div class="c-popup-address">${areaCode}</div>
          <div class='c-popup-link ${OBJECTID.trim()}____${projectName.trim()}'>查看工程</div>
        </div>
      </div>`;
  };

  function getPoiPopup(feature) {
    const div = document.createElement('div');
    // console.log(feature.graphic.attributes);
    div.innerHTML = renderPoiPopup(feature.graphic.attributes);
    return div;
  }

  const popupTemplate = new PopupTemplate({
    outFields: ['*'],
    title: '{name}',
    content: getPoiPopup,
  });

  _projectListLayer = new FeatureLayer({
    title: '项目点位',
    source: graphics,
    objectIdField: 'OBJECTID',
    outFields: ['*'],
    fields: [
      {
        name: 'OBJECTID',
        type: 'oid',
      },
      {
        name: 'areaCode',
        type: 'string',
      },
      {
        name: 'name',
        type: 'string',
      },
      {
        name: 'company',
        type: 'string',
      },

      {
        name: 'prjStatus',
        type: 'string',
      },

      {
        name: 'buildArea',
        type: 'string',
      },
      {
        name: 'invest',
        type: 'string',
      },
      {
        name: 'startDate',
        type: 'string',
      },
      {
        name: 'completeDate',
        type: 'string',
      },
      {
        name: 'totalWorkTime',
        type: 'string',
      },
      {
        name: 'category',
        type: 'string',
      },
      {
        name: 'projectId',
        type: 'string',
      },
      {
        name: 'projectName',
        type: 'string',
      },
      {
        name: 'produceValue',
        type: 'string',
      },
      {
        name: 'safeCivilizationIndex',
        type: 'string',
      },
      {
        name: 'lng',
        type: 'string',
      },
      {
        name: 'lat',
        type: 'string',
      },
      {
        name: 'calculateProduceValue',
        type: 'string',
      },
      {
        name: 'totalActualProductValue',
        type: 'string',
      },
      {
        name: 'totalPlanProductValue',
        type: 'string',
      },
      {
        name: 'rate',
        type: 'string',
      },
      {
        name: 'workPeriodPercent',
        type: 'string',
      },
      {
        name: 'workPeriodString',
        type: 'string',
      },
      {
        name: 'safeNum',
        type: 'string',
      },
    ],
    renderer: iconRenderer2,

    popupTemplate,
    elevationInfo: {
      mode: 'relative-to-scene',
    },
    labelingInfo: [
      {
        labelExpressionInfo: {
          value: ' \n\n 进度状态：{rate}  工期：{workPeriodPercent}',
          // value: '{projectName} \n\n     进度状态：{rate} \n     工期：{workPeriodPercent}',
        },
        // labelPlacement: 'center-left',
        labelPlacement: 'center-center',
        symbol: {
          type: 'label-3d',
          symbolLayers: [
            {
              type: 'text',
              material: {
                color: [255, 255, 255, 0.7],
              },
              size: 7,
              // size: 10,
            },
          ],
        },
      },
    ],
  });
  queryStations = _projectListLayer.createQuery();

  return _projectListLayer;
}
async function createMainProjectListLayer(graphics) {
  const [FeatureLayer, PopupTemplate] = await jsapi.load([
    'esri/layers/FeatureLayer',
    'esri/PopupTemplate',
  ]);
  // OBJECTID: "1438385397714911233"
  // calculateProduceValue: "31805.46"
  // id: "1438385397714911233"
  // lat: "31.46273612"
  // lng: "120.09982407"
  // name: "341省道无锡马山至宜兴周铁段工程项目"
  // num: 1
  // projectId: "1438385397714911233"
  // projectName: "341省道无锡马山至宜兴周铁段工程项目"
  // totalActualProductValue: "0.00"
  // totalPlanProductValue: "0.00"

  // console.log(graphics, '-0--0-0-0-0-0-0-0-0');
  const renderPoiPopup = attributes => {
    const {
      areaCode = '--',
      OBJECTID,
      name,
      prjStatus = '进行中',
      company,
      invest,
      buildArea,
      startDate,
      completeDate,
      safeCivilizationIndex,
      category,
      totalWorkTime,
      projectName,
      produceValue,
      lat,
      lng,
      workPeriodString,
      workPeriodPercent,
      safeNum,
      num,
      totalActualProductValue,
      totalPlanProductValue,
      calculateProduceValue,
    } = attributes;
    let _progressValue = 0;
    try {
      // _progressValue = Math.round((produceValue * 100) / invest);
    } catch (error) {}
    // _progressValue = _progressValue > 100 ? 100 : _progressValue;
    return ` <div class="c-popup">
        <div class="c-popup-status">${prjStatus}</div>
        <div class="c-popup-chart">
          ${'--'}
        </div>
        <p class="c-popup-p">
        项目名称 <span>${name}</span>
        </p>
        <p class="c-popup-p">
          实际产值： <span>${totalActualProductValue} 万元</span>
        </p>
        <p class="c-popup-p">
          计划产值： <span>${totalPlanProductValue} 万元</span>
        </p>
        <p class="c-popup-p">
          计量产值： <span>${calculateProduceValue} 万元</span>
        </p>
        <p class="c-popup-p">
          包含项目： <span>${num} 个 </span>
        </p>

      </div>`;
  };

  function getPoiPopup(feature) {
    const div = document.createElement('div');
    // console.log(feature.graphic.attributes);
    div.innerHTML = renderPoiPopup(feature.graphic.attributes);
    return div;
  }

  const popupTemplate = new PopupTemplate({
    outFields: ['*'],
    title: '{name}',
    content: getPoiPopup,
  });

  const _mainProjectListLayer = new FeatureLayer({
    title: '总项目点位',
    source: graphics,
    objectIdField: 'OBJECTID',
    outFields: ['*'],
    fields: [
      {
        name: 'OBJECTID',
        type: 'oid',
      },
      {
        name: 'name',
        type: 'string',
      },
      {
        name: 'projectName',
        type: 'string',
      },
      {
        name: 'projectId',
        type: 'string',
      },
      {
        name: 'totalActualProductValue',
        type: 'string',
      },
      {
        name: 'calculateProduceValue',
        type: 'string',
      },
      {
        name: 'totalPlanProductValue',
        type: 'string',
      },
      {
        name: 'num',
        type: 'string',
      },
    ],
    renderer: iconRenderer2,
    popupTemplate,
    elevationInfo: {
      mode: 'relative-to-scene',
    },
    labelingInfo: [
      {
        labelExpressionInfo: {
          value: ' \n\n 计量产值： {calculateProduceValue}  实际产值：{totalActualProductValue}',
        },
        labelPlacement: 'center-center',
        symbol: {
          type: 'label-3d',
          symbolLayers: [
            {
              type: 'text',
              material: {
                color: [255, 255, 255, 0.7],
              },
              size: 8,
              // size: 10,
            },
          ],
        },
      },
    ],
  });
  return _mainProjectListLayer;
}

async function projectToGraphics(projects) {
  const [Graphic, Point] = await jsapi.load(['esri/Graphic', 'esri/geometry/Point']);
  const graphics = [];
  projects.forEach(item => {
    const location = new Point({
      latitude: item['lat'],
      longitude: item['lng'],
    });
    const graphic = new Graphic({
      geometry: location,
      attributes: {
        ...item,
        OBJECTID: item.projectId,
        company: item.construct,
        areaCode: item.projectAddress,
      },
    });
    graphics.push(graphic);
    iconRenderer2.uniqueValueInfos.unshift({
      value: item.projectId,
      symbol: {
        type: 'point-3d',
        symbolLayers: [
          {
            type: 'icon',
            resource: {
              // href: './images/base_map.png',
              href: `https://portal.wccg.tech:9002/weather/billboard/${item.projectId}.svg`,
            },
            size: 190,
            // size: 126,
            outline: {
              color: 'white',
              size: 2,
            },
            anchor: 'relative',
            anchorPosition: {
              x: 0,
              y: 0.5,
            },
          },
        ],
      },
    });
  });
  return graphics;
}
async function projectToGraphics2(projects, projectInfoList) {
  const [Graphic, Point] = await jsapi.load(['esri/Graphic', 'esri/geometry/Point']);
  const graphics = [];
  const mainProj = {};
  const _mainProjList = [];
  projects.forEach(e => {
    if (!mainProj[e.projectInfoId]) {
      const info = projectInfoList.filter(p => p.id == e.projectInfoId)[0];
      mainProj[e.projectInfoId] = { ...info, lat: 0, lng: 0, num: 0 };
    }

    mainProj[e.projectInfoId].lat += +e.latitude;
    mainProj[e.projectInfoId].lng += +e.longitude;
    mainProj[e.projectInfoId].num += 1;
  });

  Object.keys(mainProj).forEach(key => {
    const _item = mainProj[key];
    const item = {
      ..._item,
      lat: (_item.lat / _item.num).toFixed(8),
      lng: (_item.lng / _item.num).toFixed(8),
      projectId: _item.id,
      name: _item.projectName || '',
    };

    _mainProjList.push(item);

    const location = new Point({
      latitude: item['lat'],
      longitude: item['lng'],
    });
    const graphic = new Graphic({
      geometry: location,
      attributes: {
        ...item,
        OBJECTID: item.projectId,
      },
    });
    graphics.push(graphic);
    iconRenderer2.uniqueValueInfos.push({
      value: item.projectId,
      symbol: {
        type: 'point-3d',
        symbolLayers: [
          {
            type: 'icon',
            resource: {
              // href: './images/base_map.png',
              href: `https://portal.wccg.tech:9002/weather/billboard/${item.projectId}.svg`,
            },
            size: 247,
            // size: 163,
            // size: 126,
            outline: {
              color: 'white',
              size: 2,
            },
            anchor: 'relative',
            anchorPosition: {
              x: 0,
              y: 0.5,
            },
          },
        ],
      },
    });
  });
  console.log(iconRenderer2, '-----iconRenderer2------');
  return [graphics, _mainProjList];
}

// 获取渲染bim模型的规则数据
function getRelatedData(projProgressList) {
  // todo 检测字段大小括号
  const checkIndex = [
    '未开始',
    '未开始（延期）',
    '执行中',
    '执行中（延期）',
    '已完成',
    '已完成（提前）',
    '已完成（延期）',
    'default',
  ];
  const checkIndexObj = checkIndex.reduce((r, e, i) => {
    r[e] = i;
    return r;
  }, {});

  let _uniqValueRender = [];
  let _projProgressInfo = {};
  let _valueExpression = 'When(';
  projProgressList.forEach((e, i) => {
    let { wbs, taskStatus = 'default', text } = e;
    let color = buildingStatusTable[taskStatus];

    let infoName = text;
    // let infoName = /-([\u4e00-\u9fa5]+)/.exec(text)[1];
    // 展示用charts数据
    if (!_projProgressInfo[infoName]) {
      _projProgressInfo[infoName] = [0, 0, 0, 0, 0, 0, 0, 0];
    }
    try {
      _projProgressInfo[infoName][checkIndexObj[taskStatus]] += 1;
    } catch (error) {
      console.log(error, text, taskStatus);
    }

    _valueExpression += ` Find(Lower('${wbs}'), Lower($feature.WBS编码)) == 0, '${wbs}', `;
    _uniqValueRender.push({
      value: `${wbs}`,
      symbol: {
        type: 'mesh-3d',
        symbolLayers: [
          {
            type: 'fill',
            material: {
              color: color,
              colorMixMode: 'replace',
            },
          },
        ],
      },
    });

    // 最后一个item时加个结尾
    if (projProgressList.length - 1 === i) {
      _valueExpression += " '其他')";
    }
  });
  return [_uniqValueRender, _valueExpression, _projProgressInfo];
}

// todo 演示使用数据
async function _getInitRender(projectId) {
  //  async function getInitRender(projectId = '1296256020068786178') {
  const data = await getBuildingStatus(projectId);
  const _uniqValueRender = [];

  data.forEach(wbs => {
    _uniqValueRender.push({
      value: `${wbs}`,
      symbol: {
        type: 'mesh-3d',
        symbolLayers: [
          {
            type: 'fill',
            material: {
              color: [255, 255, 255, 0],
              // color: [255, 0, 0, 1],
              colorMixMode: 'replace',
            },
          },
        ],
      },
    });
  });
  console.log(_uniqValueRender, 'init---------');
  return _uniqValueRender;
}

// 高亮feature layer中的 graphic
async function highlightPoint(sqlStr = '', goto = false) {
  console.log(sqlStr);
  const view = await viewUtils.isViewReady();
  view.whenLayerView(_projectListLayer).then(layerView => {
    // queryStations.where = `${_key}='${_value}'`;
    queryStations.where = sqlStr;
    _projectListLayer.queryFeatures(queryStations).then(function(result) {
      try {
        if (highlightSelect.length) {
          highlightSelect.forEach(e => e.remove());
          highlightSelect = [];
        }

        if (goto) {
          view.goTo(result.features[0]);
        }

        result.features.forEach(e => {
          highlightSelect.push(layerView.highlight(e.attributes['OBJECTID']));
        });
      } catch (error) {}
    });
  });
}

// 总部位置图层
async function createCenterLayer() {
  const [Graphic, Point, FeatureLayer] = await jsapi.load([
    'esri/Graphic',
    'esri/geometry/Point',
    'esri/layers/FeatureLayer',
  ]);

  var iconRenderer = {
    type: 'simple',
    symbol: {
      type: 'point-3d',
      symbolLayers: [
        {
          type: 'icon',
          resource: {
            href: './images/mark.svg',
          },
          size: 180,
          // size: 126,
          outline: {
            color: 'white',
            size: 2,
          },
          anchor: 'relative',
          anchorPosition: {
            x: 0,
            y: 0.5,
          },
        },
      ],
    },
  };

  return new FeatureLayer({
    title: '无锡市城市重点建设项目管理中心',
    source: [
      new Graphic({
        geometry: new Point({
          longitude: '120.29945',
          latitude: '31.575001',
        }),
        attributes: {
          name: '无锡市城市重点建设项目管理中心',
          OBJECTID: '无锡市城市重点建设项目管理中心',
        },
      }),
    ],

    popupEnabled: false,
    objectIdField: 'OBJECTID',
    outFields: ['*'],
    fields: [
      {
        name: 'OBJECTID',
        type: 'oid',
      },
      {
        name: 'name',
        type: 'string',
      },
    ],
    renderer: iconRenderer,
    elevationInfo: {
      mode: 'relative-to-scene',
    },
    labelingInfo: [
      {
        labelExpressionInfo: {
          value: '{name}',
        },
        labelPlacement: 'center-center',
        symbol: {
          type: 'label-3d',
          symbolLayers: [
            {
              type: 'text',
              material: {
                color: 'white',
              },
              size: 10,
            },
          ],
        },
      },
    ],
  });
}

const KanbanModel = {
  namespace: 'kanban',

  state: {
    level: 'project',
    projList: [], // 所有的项目信息
    mainProjList: [],
    companyList: [], //所有的公司信息
    workingPpl: [], // 工作人员信息
    projProgressList: [], //项目进度信息
    projProgressBeforeActualList: [], //用于对比的真实截至日期列表
    projAndModelNumList: [], // 项目模型数量统计
    initUniqValueRender: [], // 初始状态时构件做wbs编码的颜色唯一值渲染的render
    uniqValueRender: [], // 构件做wbs编码的颜色唯一值渲染的render
    valueExpression: '', // 唯一值渲染的兼容写法c-1-2 兼容c-1-2-3
    projProgressInfo: {}, // 项目进度分类统计
    curCompany: '', // 当前查看的公司
    safeIndexArr: [], // 安全指数信息
    isInitRendered: false,
  },

  effects: {
    // 获取项目列表
    getProjectList: [
      function*({ payload }, { put, select }) {
        const [data, data2, allSafetyIndexData] = yield Promise.all([
          findProjectInfo(),
          getProduceValueAndCalculate(),
          listAllSafetyIndex(),
        ]);
        const [projIdToproduceValue, lastRateItem] = data2.reduce(
          (r, e) => {
            let rateNum = (
              ((e.totalActualProductValue - e.totalPlanProductValue) * 100) /
              e.totalPlanProductValue
            ).toFixed(0);

            let rate = '筹备中';
            if (rateNum > 0) {
              rate = '超前 ' + rateNum + '%';
            } else if (rateNum < 0) {
              rate = '滞后 ' + rateNum.toString().slice(1) + '%';
            } else if (e.totalActualProductValue) {
              rate = '超前 0%';
            }
            r[0][e.projectId] = {
              calculateProduceValue: e.calculateProduceValue,
              totalActualProductValue: e.totalActualProductValue,
              totalPlanProductValue: e.totalPlanProductValue,
              rate,
            };
            if (rateNum < r[1].rateNum || !r[1].rateNum) {
              r[1] = {
                rateNum,
                item: e,
              };
            }
            return r;
          },
          [{}, {}],
        );

        const safeIndexArr = allSafetyIndexData.sort(
          (a, b) => b.safeProduceIndex - a.safeProduceIndex,
        );
        let lastRatePrjId = lastRateItem.item.projectId;
        let lastSafePrjId = safeIndexArr[safeIndexArr.length - 1].projectId;

        // console.log(iconRenderer2.uniqueValueInfos[0]);
        // console.log(iconRenderer2.uniqueValueInfos[1]);
        iconRenderer2.uniqueValueInfos[0].value = lastSafePrjId;
        iconRenderer2.uniqueValueInfos[1].value = lastRatePrjId;
        iconRenderer2.uniqueValueInfos[0].symbol.symbolLayers[0].resource.href = `https://portal.wccg.tech:9002/weather/billboard/${lastSafePrjId}_red.svg`;
        iconRenderer2.uniqueValueInfos[1].symbol.symbolLayers[0].resource.href = `https://portal.wccg.tech:9002/weather/billboard/${lastRatePrjId}_yellow.svg`;
        console.log(safeIndexArr);
        // add alias 增加属性别名
        data.data.data.forEach(e => {
          e.lng = e.longitude;
          e.lat = e.latitude;
          e.code = e.transProjectCode;
          e.name = e.fullName;
          e.startDate = e.startTime;
          // e.startDate = e.createTime;
          e.completeDate = e.deadlineTime;
          e.address = e.projectAddress; // 项目地址
          e.invest = e.contractorAmount; // 项目投资总额，合同金额 （万元）
          e.landArea = e.buildArea; // 项目面积
          e.prjStatus = e.projectStatus; // 项目状态
          e.category = e.projectType; // 项目分类
          e.safeNum = 0; // 项目分类
          try {
            e.safeNum = (
              safeIndexArr.filter(data => data.projectId === e.projectId)[0].safeProduceIndex * 100
            ).toFixed();
          } catch (error) {}

          let extraData = projIdToproduceValue[e.projectId];
          e.calculateProduceValue = extraData.calculateProduceValue;
          e.totalActualProductValue = extraData.totalActualProductValue;
          e.totalPlanProductValue = extraData.totalPlanProductValue;
          e.rate = extraData.rate;
          const daysFromStart = moment().diff(e.startDate, 'days');
          const totalWorkTimeNum = e.totalWorkTime.slice(0, -1);
          e.workPeriodPercent =
            extraData.rate === '筹备中'
              ? '-'
              : ((+daysFromStart * 100) / totalWorkTimeNum).toFixed() + '%';
          e.workPeriodString = `${daysFromStart}/${e.totalWorkTime}`;

          // e.lastRate= lastRateItem.item.projectId === e.projectId ? '滞后最多' :''
        });

        if (data.data.data.length > 0) {
          // 更新model里的值
          yield put({
            type: 'updateState',
            payload: {
              projList: data.data.data,
              safeIndexArr,
            },
          });

          return data.data.data;
        }
      },
      { type: 'throttle', ms: 10 },
    ],

    // 获取公司列表
    // 获取项目列表
    *getCompanyList({ payload }, { put, select }) {
      const data = yield getCompanys();
      if (data.data.data.length > 0) {
        // 更新model里的值
        yield put({
          type: 'updateState',
          payload: {
            companyList: data.data.data,
          },
        });
        return data.data.data;
      }
    },

    // 主页面 获取项目列表并在地图上渲染mark
    *getProjectListAndRender({ payload }, { put, call }) {
      const data = yield yield put({ type: 'getProjectList' });
      yield yield put({ type: 'getCompanyList' });
      // 数据上图，前端创建featurelayer自定义renderer
      const graphics = yield projectToGraphics(data);
      const projListLyr = yield createProjectListLayer(graphics);
      console.log(graphics, projListLyr);
      projListLyr.visible = false;

      const dataForMainData = yield getProjectProgressStat();
      const [graphics2, mainProjList] = yield projectToGraphics2(
        data,
        dataForMainData.data.data.resProjectInfoDto.projectInfoList,
      );
      const mainProjLyr2 = yield createMainProjectListLayer(graphics2);
      const centerPointLayer = yield createCenterLayer();
      const view = yield viewUtils.isViewReady();
      view.map.add(centerPointLayer);
      view.map.add(projListLyr);
      view.map.add(mainProjLyr2);
      // view.map.addMany([centerPointLayer, projListLyr, mainProjLyr2]);
      yield put({
        type: 'updateState',
        payload: {
          mainProjList,
        },
      });
      yield call(initEchartsLayer, mainProjList);
    },

    // 获取当前项目对象
    *getCurProj({ payload }, { put, select, call }) {
      const data = yield yield put({ type: 'getProjectList' });
      const { curProjId } = yield select(store => store.app);
      if (!curProjId) return;
      let curProj = yield call(list => list.filter(e => e.projectId === curProjId)[0], data);
      yield put({
        type: 'app/updateState',
        payload: {
          curProj,
        },
      });
      return curProj;
    },

    // 获取工作人员信息
    *getWorkingPplInfo({ payload }, { put, select, call }) {
      const { curProjId, curProj } = yield select(store => store.app);
      const data = yield call(findUserInfo, curProj.transProjectCode);
      yield put({ type: 'updateState', payload: { workingPpl: data.data.data } });
      console.log(data);
    },

    // 获取进度信息全部
    *getProjProgressInfo({ payload }, { put, select, call }) {
      const { curProj } = yield select(store => store.app);
      const data = yield call(getProjProgress, curProj.projectId);
      yield put({ type: 'updateState', payload: { projProgressList: data.data.data } });
      const [uniqValueRender, valueExpression, projProgressInfo] = yield call(
        getRelatedData,
        data.data.data,
      );
      yield put({
        type: 'updateState',
        payload: { uniqValueRender, valueExpression, projProgressInfo },
      });
    },

    // 获取项目模型数量
    *getProjandModelNum({ payload }, { put, select, call }) {
      const data = yield call(getProjandModelNum);
      yield put({ type: 'updateState', payload: { projAndModelNumList: data } });
    },

    // 设置当前公司
    *setLastIndexCompany({ payload }, { put, select, call }) {
      // _projectListLayer.renderer =

      const companyList = yield select(store => store.kanban.companyList);

      try {
        let curProjsId = companyList
          .filter(e => e.companyName === payload.curCompany)[0]
          .projects.map(e => `'${e.projectId}'`);

        yield call(highlightPoint, `projectId in (${curProjsId})`);
      } catch (error) {
        console.error(error);
      }
      yield put({ type: 'updateState', payload: { curCompany: payload.curCompany } });
    },

    // 设置当前公司
    *setCurCompany({ payload }, { put, select, call }) {
      const companyList = yield select(store => store.kanban.companyList);

      try {
        let curProjsId = companyList
          .filter(e => e.companyName === payload.curCompany)[0]
          .projects.map(e => `'${e.projectId}'`);

        yield call(highlightPoint, `projectId in (${curProjsId})`);
      } catch (error) {
        console.error(error);
      }
      yield put({ type: 'updateState', payload: { curCompany: payload.curCompany } });
    },

    // 触发高亮
    *setHighlight({ payload }, { put, select, call }) {
      yield call(highlightPoint, `${payload.key}='${payload.value}'`, payload.goto);
    },

    // 获取初始化渲染的唯一值渲染值
    *getInitRender({ payload }, { put, select, call }) {
      const curProjId = yield select(store => store.app.curProjId);
      const initUniqValueRender = yield call(_getInitRender, curProjId);
      yield put({
        type: 'updateState',
        payload: {
          initUniqValueRender,
        },
      });

      const addedBimNameList = yield select(store => store.bimmodel.addedBimNameList);
      // 获取当前加载的bim模型列表
      const view = yield viewUtils.isViewReady();
      let lyrs = addedBimNameList.reduce((r, layerName) => {
        const lyr = view.map.layers.find(l => l.title === layerName);
        if (lyr) r.push(lyr);
        return r;
      }, []);
      lyrs.forEach(lyr => {
        // 不渲染的例外
        if (['南部通道宜马三场', '宜马项目三场临建'].indexOf(lyr.title) !== -1) return;
        lyr.allSublayers.forEach(subLayer => {
          if (subLayer.type === 'building-component') {
            subLayer.renderer = {
              type: 'unique-value',
              field: 'WBS编码',
              uniqueValueInfos: initUniqValueRender,
            };
          }
        });
      });
      yield put({
        type: 'updateState',
        payload: {
          isInitRendered: true,
        },
      });

      return initUniqValueRender;
    },
  },

  reducers: {
    updateState(state, { payload }) {
      return { ...state, ...payload };
    },
  },
};

export default KanbanModel;
